/**
 *
 */
package org.examcity.springmvc.controllers;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;
import org.examcity.domain.UserRepository;
import org.examcity.domain.User;

@Controller
@SessionAttributes("user")
public class UserController {

	@Autowired
	private UserRepository userRepository;

	@RequestMapping("/list.do")
	public ModelMap list(ModelMap model) {
		model.addAttribute("userList", userRepository.findAll());
		return model;
	}

	@RequestMapping("/view.do")
	public ModelMap view(@RequestParam("userId") long userId, ModelMap model) {
		model.addAttribute("user", userRepository.find(userId));
		return model;
	}

	@RequestMapping("/delete.do")
	public String delete(@RequestParam("userId") long userId) {
		userRepository.remove(userRepository.find(userId));
		return "redirect:list.html";
	}

	@RequestMapping(value = { "/create.do", "/update.do" }, method = RequestMethod.GET)
	public String setupForm(ModelMap model, WebRequest request) {
		String userId = request.getParameter("userId");
		if (userId == null) {
			model.addAttribute("user", new User());
		} else {
			model.addAttribute("user", userRepository.find(Long.parseLong(userId)));
		}
		return "form";
	}

	@RequestMapping(value = "/form.do", method = RequestMethod.POST)
	public String submit(@ModelAttribute("user") User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return "form";
		} else {
			userRepository.merge(user);
			return "redirect:list.do";
		}
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}
}
